const fs = require('fs')
const puppeteer = require('puppeteer')
const { readFile } = require('fs/promises')

exports.crawler = async function (key = null, match) {
  const pages = JSON.parse(await readFile('./pages.json'))

  if (!fs.existsSync('screenshots')) {
    fs.mkdirSync('screenshots')
  }

  let browser = null
  let res = []

  if (key == null || pages.find((e) => e.name.match(new RegExp(key, 'ig')))) {
    try {
      console.log(`✅ 启动浏览器 - puppeteer`)
      const pc = puppeteer.devices['iPad Pro landscape']
      const iPhone = puppeteer.devices['iPhone 11 Pro Max']

      browser = await puppeteer.launch({
        headless: true,
        ignoreHTTPSErrors: true,
        userDataDir: './tmp/',
        args: [
          "--proxy-server='direct://'",
          '--proxy-bypass-list=*',
          '--ignore-certificate-errors',
          '--no-sandbox',
          '--disable-infobars',
          '--disable-setuid-sandbox',
        ],
      })

      const page = await browser.newPage()
      await page.emulate(pc)

      const loginURL = 'https://admin.farmersworld.vip/?orgId=1'
      await page.goto(loginURL)
      const isLogin = await page.$eval('nav.sidemenu', (elem) => {
        return (
          window.getComputedStyle(elem).getPropertyValue('display') !== 'none' && elem.offsetHeight
        )
      })
      if (!isLogin) {
        console.log(`✅ 登录 - (${loginURL})`)
        await page.type('input[name="user"]', 'user')
        await page.type('#current-password', 'feifei123123')

        await Promise.all([page.click('button.css-1wkrg9j-button'), page.waitForNavigation()])
      }

      for (let { id, name, url, auto, mobile } of pages) {
        if (mobile) {
          await page.emulate(iPhone)
        }
        if (key) {
          // 单点消息
          if (name.match(new RegExp(key, 'ig'))) {
            if (match) {
              url = url.replace('gagxi.wam', match)
            }
            await page.goto(url, { waitUntil: 'networkidle0' })
            await page.screenshot({ path: `screenshots/${id}.png`, type: 'png' })
            res.push({ id, name, url })
            console.log(`✅ ${name} - (${url})`)
          }
        } else {
          // 定时任务
          if (auto) {
            await page.goto(url, { waitUntil: 'networkidle0' })
            await page.screenshot({ path: `screenshots/${id}.png`, type: 'png' })
            res.push({ id, name, url })
            console.log(`✅ ${name} - (${url})`)
          }
        }
      }
    } catch (err) {
      console.log(`❌ Error: ${err.message}`)
    } finally {
      await browser.close()
      console.log(`\n🎉 GitHub profile screenshots captured.`)
    }
  }
  return res
}
